package com.xmutca.micro.uaa.security;

import com.xmutca.micro.uaa.exception.IllegalTokenException;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by chunchengpeng on 17/7/27.
 */
public class AuthenticationTokenFilter extends UsernamePasswordAuthenticationFilter {

    @Value("${micro.token.header}")
    private String tokenHeader;

    private JwtTokenFactory jwtTokenFactory;

    private UserDetailsService userDetailsService;

    public AuthenticationTokenFilter(JwtTokenFactory jwtTokenFactory, UserDetailsService userDetailsService, AuthenticationManager authenticationManager) {
        this.jwtTokenFactory = jwtTokenFactory;
        this.userDetailsService = userDetailsService;
        setAuthenticationManager(authenticationManager);
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) req;
        String token = httpRequest.getHeader(tokenHeader);
        if (StringUtils.isNotBlank(token) && SecurityContextHolder.getContext().getAuthentication() == null) {
            Claims claims = jwtTokenFactory.getClaimsFromToken(token);
            UserDetails userDetails = userDetailsService.loadUserByUsername(claims.getSubject());
            if (!jwtTokenFactory.validateToken(claims, httpRequest)) {
                //token非法
                throw new IllegalTokenException();
            }

            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        chain.doFilter(req, res);
    }
}
